package com.weepal.pavement.mqtt.demo.analysis.dataSender;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.weepal.pavement.mqtt.demo.vo.MqttDevices;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class MQSender {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void send(MqttDevices devices, String field, String jsonKey, LinkedList<String> data) {
        try {
            Object obj = rabbitTemplate.convertSendAndReceive(devices.getExchange(), devices.getRoutingKey(), array2map(field, data, jsonKey));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    private final String FLAG = "\"%s\":";

    private String array2map(String field, LinkedList<String> data, String jsonKey) throws JsonProcessingException {
        String[] split = field.split(",");
        int size = split.length;
        ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>(8);
        for (int i = 0; i < size; i++) {
            String val = data.removeFirst();
            String key = split[i];
            map.put(key, val);
        }
        ObjectMapper objectMapper = new ObjectMapper();
        jsonKey = String.format(FLAG, jsonKey);
        jsonKey += objectMapper.writeValueAsString(map);
        return jsonKey;
    }
}
